//
//  ChooseLocalViewController.m
//  Findif
//
//  Created by Mac on 2019/1/24.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "ChooseLocalViewController.h"
//地图
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <MapKit/MapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "MapLocalTableViewCell.h"

@interface ChooseLocalViewController ()<UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,AMapSearchDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UITextField * searchTextfiled;
@property (nonatomic, strong)AMapSearchAPI * search;
@property (nonatomic, strong)NSArray * localModelArray;

@end

@implementation ChooseLocalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    [self setupNav];
    [self setupUI];
    [self initSearch];
}

- (void)returnLocalName:(SelectedLocalBlock)block{
    
    self.selectedLocalBlock = block;
}


- (void)setupNav{
    
    self.title = @"所在位置";
    
    UIButton * backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 15 * SCREENH6)];
    
    [backButton setTitle:@"取消" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToView) forControlEvents:UIControlEventTouchUpInside];
    backButton.titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    [backButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
    
    
//    UIButton * finishButton = [[UIButton alloc] init];
//
//    //    backButton.frame = CGRectMake(0 , 0 , 65 * SCREENH6, 20 * SCREENH6);
//    [finishButton setTitle:@"完成" forState:UIControlStateNormal];
//    finishButton.titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
//    [finishButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
//
//    [finishButton addTarget:self action:@selector(clickFinishButton) forControlEvents:UIControlEventTouchUpInside];
//
//    UIBarButtonItem * nextButton = [[UIBarButtonItem alloc] initWithCustomView:finishButton];
//
//    self.navigationItem.rightBarButtonItem = nextButton;
    
}


- (void)setupUI{
    
    UITextField * searchTextfiled = [[UITextField alloc] initWithFrame:CGRectMake(10 * SCREENH6, topHeight + 10 * SCREENH6, 355 * SCREENH6, 30 * SCREENH6)];
    
    searchTextfiled.borderStyle = UITextBorderStyleRoundedRect;
    searchTextfiled.backgroundColor = ZRWhiteColor;
    //设置光标颜色
    searchTextfiled.tintColor = ZRBlackColor;
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xbebebe);
    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    searchTextfiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"搜索附近位置" attributes:attrs];
    searchTextfiled.textColor = ZRBlackColor;
    searchTextfiled.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    searchTextfiled.leftViewMode = UITextFieldViewModeAlways;
    searchTextfiled.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15 * SCREENH6];
    UIView * rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 35 * SCREENH6, 20 * SCREENH6)];
    UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(5, 0, 18 * SCREENH6, 18 * SCREENH6)];//WithImage:[UIImage imageNamed:@"手机号"]];
    image.image = [UIImage imageNamed:@"搜索"];
    [rightView addSubview:image];
    searchTextfiled.leftView = rightView;
    searchTextfiled.leftViewMode = UITextFieldViewModeAlways;
    searchTextfiled.returnKeyType = UIReturnKeySearch;
    searchTextfiled.delegate = self;
    
    self.searchTextfiled = searchTextfiled;
    
    [self.view addSubview:self.searchTextfiled];
    
    
    
    self.search = [AMapSearchAPI new];
    self.search.delegate = self;
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topHeight + 50 * SCREENH6, kScreenW, kScreenH - topHeight - 50 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ZRWhiteColor;
    tableView.rowHeight = 60 * SCREENH6;
    //    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[MapLocalTableViewCell class] forCellReuseIdentifier:@"PushMapLocalTableViewCell"];
    
    [self.view addSubview:self.tableView];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //    NSLog(@"aaa===%lu",(unsigned long)self.localModelArray.count);
    return self.localModelArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MapLocalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PushMapLocalTableViewCell" forIndexPath:indexPath];
    
    AMapPOI * poi = self.localModelArray[indexPath.row];
    
    cell.name = poi.name;
    cell.addrss = poi.address;
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MapLocalTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    if (self.selectedLocalBlock != nil) {
        
        AMapPOI * poi = self.localModelArray[indexPath.row];
        AMapGeoPoint *location = poi.location;
        NSString * longitude = [NSString stringWithFormat:@"%f",location.longitude];
        NSString * latitude = [NSString stringWithFormat:@"%f",location.latitude];
        
        NSDictionary * dict = @{@"longitude":longitude,@"latitude":latitude,@"name":cell.name};
        
        self.selectedLocalBlock(dict);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)initSearch{
    
    //    if (self.currentLocation == nil || self.search == nil) {
    //
    //        return;
    //    }
    
    AMapPOIAroundSearchRequest * request = [AMapPOIAroundSearchRequest new];
    
    CGFloat lat = [DEF_GET_OBJECT(@"lat") floatValue];
    CGFloat lon = [DEF_GET_OBJECT(@"lon") floatValue];
    
    request.location = [AMapGeoPoint locationWithLatitude:lat longitude:lon];
    
    //    switch (self.selectedTag) {
    //        case 1:
    //            request.types = @"写字楼";
    //            break;
    //        case 2:
    //            request.types = @"小区";
    //            break;
    //        case 3:
    //            request.types = @"学校";
    //            break;
    //        default:
    //            request.types = @"汽车服务";
    //            break;
    //    }
    request.types = @"写字楼|小区|学校|商务住宅";
    request.sortrule = 0;
    request.requireSubPOIs = YES;
    request.radius = 1000;
    
    [self.search AMapPOIAroundSearch:request];
}

- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    //
    //
    //    for (AMapPOI * poi in response.pois) {
    //
    //        NSLog(@"==%@",poi.name);
    //        NSLog(@"==%@",poi.address);
    //
    //    }
    if ((response.pois.count == 0)) {
        
        return;
    }
    
    self.localModelArray = response.pois;
    
    [self.tableView reloadData];
    
    //    NSLog(@"res====%@",response.pois);
}

//实现UITextField代理方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];//取消第一响应者
    
    
    AMapPOIAroundSearchRequest * request = [AMapPOIAroundSearchRequest new];
    
    CGFloat lat = [DEF_GET_OBJECT(@"lat") floatValue];
    CGFloat lon = [DEF_GET_OBJECT(@"lon") floatValue];
    
    request.location = [AMapGeoPoint locationWithLatitude:lat longitude:lon];

    request.keywords = textField.text;
    request.sortrule = 0;
    request.requireSubPOIs = YES;
//    request.radius = 1000;
    
    [self.search AMapPOIAroundSearch:request];
    
//    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
//
//    request.keywords            = textField.text;
//    request.city                = @"北京";
//    request.types               = @"高等院校";
//    request.requireExtension    = YES;
//
//    /*  搜索SDK 3.2.0 中新增加的功能，只搜索本城市的POI。*/
//    request.cityLimit           = YES;
//    request.requireSubPOIs      = YES;
    
    return YES;
}

//- (void)clickFinishButton{
//    
//    
//}


- (void)backToView{
    
    if (self.selectedLocalBlock != nil) {
        
        NSDictionary * dict = @{@"name":@"所在位置"};
        
        self.selectedLocalBlock(dict);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
